#pragma once

#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <string>
#include <fcntl.h>
#include <unistd.h>
#define FIFO_FILE "fifo"

#define FILENAME "fifo"
#define PATH "."

class NamedFifo
{
public:
    NamedFifo(const std::string &path, const std::string &name)
        : _path(path), _name(name)
    {
        _fifoname = _path + "/" + _name;
        umask(0);
        // int n = mkfifo(FIFO_FILE, 0666);
        int n = mkfifo(_fifoname.c_str(), 0666);
        if (n < 0)
        {
            std::cerr << "mkfifo error" << std::endl;
        }
        else
        {
            std::cerr << "mkfifo success" << std::endl;
        }
    }
    ~NamedFifo()
    {
        int n = unlink(_fifoname.c_str());
        if (n == 0)
        {
            std::cout << "remove fifo success" << std::endl;
        }
        else
        {
            std::cout << "remove fifo failed" << std::endl;
        }
    }

private:
    std::string _path;
    std::string _name;
    std::string _fifoname;
};

class FileOper
{
public:
    FileOper(const std::string &path, const std::string &name)
        : _path(path), _name(name), _fd(-1)
    {
        _fifoname = _path + "/" + _name;
    }
    void OpenForRead()
    {
        _fd = open(FIFO_FILE, O_RDONLY);
        if (_fd < 0)
        {
            std::cerr << "open fifo error" << std::endl;
            return;
        }
        std::cout << "open fifo success" << std::endl;
    }
    void OpenForWrite()
    {
        _fd = open(FIFO_FILE, O_WRONLY);
        if (_fd < 0)
        {
            std::cerr << "open fifo error" << std::endl;
            return;
        }
        std::cout << "open fifo success" << std::endl;
    }
    void Write()
    {
        pid_t id = getpid();
        int cnt = 1;
        while (true)
        {
            std::cout << "please Enter#";
            std::string message;
            // std::cin>>message;
            std::getline(std::cin, message);
            message += (",message number:" + std::to_string(cnt++) + "[" + std::to_string(id) + "]");

            int n = write(_fd, message.c_str(), message.size());
            if (n > 0)
            {
            }
        }
    }
    void Read()
    {
        char buffer[1024];
        while (true)
        {
            int num = read(_fd, buffer, sizeof(buffer) - 1);
            if (num > 0)
            {
                buffer[num] = 0;
                std::cout << "client say:" << buffer << std::endl;
            }
            else if (num == 0)
            {
                std::cout << "if client quit,server quit too" << std::endl;
                break;
            }
            else
            {
                std::cout << "read error" << std::endl;
                break;
            }
        }
    }
    void Close()
    {
        if (_fd > 0)
            close(_fd);
    }
    ~FileOper()
    {
    }

private:
    std::string _path;
    std::string _name;
    std::string _fifoname;
    int _fd;
};